//
//  WeiteTieZiViewController.m
//  Liuhe
//
//  Created by zr on 2018/8/8.
//  Copyright © 2018年 zr. All rights reserved.
//

#import "WeiteTieZiViewController.h"

@interface WeiteTieZiViewController ()<UITextViewDelegate,UIImagePickerControllerDelegate, UINavigationControllerDelegate>{
    
    UIImagePickerController *_imagePickerController;
}

@property (nonatomic, weak)UITextView * textView;
@property (nonatomic, weak)UIButton * addButton;
@property (nonatomic, strong)UIAlertController * alertVC;
@property (nonatomic, copy)NSString * images;

@end

@implementation WeiteTieZiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = ColorWithRGB(0xF2F3F5);
    
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
    
    
    [self setupNav];
    [self setupUI];
    [self setupAlertVC];
}


- (void)setupNav{
    
    self.title = @"发贴";
    
    UIButton * backButton = [[UIButton alloc] init];
    
//    backButton.frame = CGRectMake(0, 0, 12 * SCREENH6, 20 * SCREENH6);
    backButton.size = CGSizeMake(20 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
    
    
    UIButton * backButton1 = [[UIButton alloc] init];
    
    //    backButton.frame = CGRectMake(0 , 0 , 65 * SCREENH6, 20 * SCREENH6);
    [backButton1 setTitle:@"发布" forState:UIControlStateNormal];
    backButton1.titleLabel.font = [UIFont boldSystemFontOfSize:15 * SCREENH6];
    [backButton1 setTitleColor:BLACK_COLOR forState:UIControlStateNormal];
    
    [backButton1 addTarget:self action:@selector(ClickSureButton) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * nextButton = [[UIBarButtonItem alloc] initWithCustomView:backButton1];
    
    self.navigationItem.rightBarButtonItem = nextButton;
    
}

- (void)backToView{
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)setupUI{
    // 创建textView
    UITextView *textView =[[UITextView alloc]init];
    textView.backgroundColor= WHITE_COLOR;
    textView.text = @"来吧，尽情发挥吧！";
    textView.font = [UIFont systemFontOfSize:14 * SCREENH6];
    textView.textColor = ColorWithRGB(0xbebebe);
    textView.delegate = self;
//    textView.layer.borderColor = [ColorWithRGB(0xbebebe) CGColor];
//    textView.layer.borderWidth = 1.0f;
    
    self.textView = textView;
    [self.view addSubview:self.textView];
    
    
    UIButton * addButton = [UIButton new];
    
    [addButton setImage:ImageNamed(@"655654465") forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(clickAddButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.addButton = addButton;
    
    [self.view addSubview:self.addButton];
}


-(void)viewDidLayoutSubviews{
 
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
//        make.trailing.mas_equalTo(self.view).offset(-15 * SCREENH6);
        make.leading.trailing.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.height.mas_equalTo(150 * SCREENH6);
    }];
    
    [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.textView);
        make.top.mas_equalTo(self.textView.mas_bottom).offset(20 * SCREENH6);
        make.width.height.mas_equalTo(80 * SCREENH6);
    }];
}


- (void)clickAddButton{
    
    [self presentViewController:self.alertVC animated:YES completion:nil]; 
}


- (void)setupAlertVC{
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"选择照片方式" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [self.alertVC addAction:camerAction];
    [self.alertVC addAction:albumsAction];
    [self.alertVC addAction:cancelAction];
    
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)editingInfo

{
    
    [self.addButton setImage:image forState:UIControlStateNormal];
    
    NSData *frontImageData = UIImageJPEGRepresentation(image,0.5);
    
    NSString * token = DEF_GET_OBJECT(@"token");
    
    NSDictionary * dic = @{@"files":frontImageData,@"token":token};
    
    [[NetworkTool sharedTools] POST:@"/files/Image/upload" parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat  = @"yyyyMMddHHmmss";
        NSString *str  = [formatter stringFromDate:[NSDate date]];
        NSString *fileName  = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:frontImageData name:@"image" fileName:fileName mimeType:@"image/png"];
        
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"===%@",responseObject);
        
        int code = [responseObject[@"code"] intValue];
        
        if (code == 201){
            
            NSArray * arr = responseObject[@"data"];
            NSDictionary * dict = arr.firstObject;
            self.images = [NSString stringWithFormat:@"%@",dict[@"link"]];
        }else{
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

//进入拍摄页面点击取消按钮

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}



- (void)textViewDidEndEditing:(UITextView *)textView
{
    
    if(textView.text.length < 1){
        textView.text = @"来吧，尽情发挥吧！";
        textView.textColor = ColorWithRGB(0xbebebe);
    }else{
        
        [textView resignFirstResponder];
    }
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if([textView.text isEqualToString:@"来吧，尽情发挥吧！"]){
        textView.text=@"";
        textView.textColor = BLACK_COLOR;
    }
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.textView resignFirstResponder];
    //    [self.textView endEditing:YES];
}


- (void)ClickSureButton{
    
    SHOWHUD;
    
    NSString * token = DEF_GET_OBJECT(@"token");
//    NSLog(@"===%@",token);
    
    NSDictionary * dict = @{@"project_id":@"1",@"token":token,@"pid":@"12",@"depict":self.textView.text,@"imglist":self.images};
    
    
    [[NetworkTool sharedTools] POST:@"/api/circle" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        NSLog(@"res====%@",responseObject);
        HIDDENHUD;
        
        int status = [responseObject[@"code"] intValue];
        
        if (status == 200) {
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"恭喜你，发布成功！快去看看吧！"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      [self.navigationController popViewControllerAnimated:YES];
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseObject[@"msg"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        HIDDENHUD;
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
